<template>
  <div class="report-container">
    <!-- 查询条件 -->
    <el-card class="search-card">
      <el-form :model="searchForm" ref="searchFormRef" :inline="true">
        <el-form-item label="统计维度" prop="dimension">
          <el-select v-model="searchForm.dimension" placeholder="请选择统计维度" style="width: 180px">
            <el-option label="按日统计" value="DAY" />
            <el-option label="按周统计" value="WEEK" />
            <el-option label="按月统计" value="MONTH" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围" prop="dateRange">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="产品类别" prop="productCategory">
          <el-select v-model="searchForm.productCategory" placeholder="请选择产品类别" clearable style="width: 180px">
            <el-option label="电子产品" value="ELECTRONICS" />
            <el-option label="机械产品" value="MACHINERY" />
            <el-option label="化工产品" value="CHEMICAL" />
          </el-select>
        </el-form-item>
        <el-form-item label="检验类型" prop="inspectionType">
          <el-select v-model="searchForm.inspectionType" placeholder="请选择检验类型" clearable style="width: 180px">
            <el-option label="首件检验" value="FIRST_PIECE" />
            <el-option label="过程检验" value="PROCESS" />
            <el-option label="最终检验" value="FINAL" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" :icon="Download" @click="handleExport">导出报表</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-value inspection-count">{{ statsData.totalInspections }}</div>
              <div class="stat-label">检验批次</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-value pass-rate">{{ statsData.overallPassRate }}%</div>
              <div class="stat-label">总体合格率</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-value defect-rate">{{ statsData.defectRate }}%</div>
              <div class="stat-label">不良率</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-value rework-rate">{{ statsData.reworkRate }}%</div>
              <div class="stat-label">返工率</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 图表区域 -->
    <div class="charts-container">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>质量趋势图</span>
              </div>
            </template>
            <div ref="qualityTrendChart" class="chart" style="height: 300px;"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>不合格原因分析</span>
              </div>
            </template>
            <div ref="defectReasonChart" class="chart" style="height: 300px;"></div>
          </el-card>
        </el-col>
      </el-row>
      
      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>产品质量对比</span>
              </div>
            </template>
            <div ref="productQualityChart" class="chart" style="height: 300px;"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>检验类型分布</span>
              </div>
            </template>
            <div ref="inspectionTypeChart" class="chart" style="height: 300px;"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 详细数据表格 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>质量检验明细</span>
        </div>
      </template>
      
      <el-table :data="tableData" style="width: 100%" v-loading="loading" border>
        <el-table-column prop="date" label="日期" />
        <el-table-column prop="productName" label="产品名称" />
        <el-table-column prop="inspectionType" label="检验类型">
          <template #default="scope">
            <el-tag :type="getInspectionTypeTag(scope.row.inspectionType)">
              {{ getInspectionTypeText(scope.row.inspectionType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="inspectionQuantity" label="检验数量" align="right" />
        <el-table-column prop="passQuantity" label="合格数量" align="right">
          <template #default="scope">
            <span class="pass-quantity">{{ scope.row.passQuantity }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="failQuantity" label="不合格数量" align="right">
          <template #default="scope">
            <span class="fail-quantity" v-if="scope.row.failQuantity > 0">{{ scope.row.failQuantity }}</span>
            <span v-else>0</span>
          </template>
        </el-table-column>
        <el-table-column prop="passRate" label="合格率" align="right">
          <template #default="scope">
            <span :class="getPassRateClass(scope.row.passRate)">{{ scope.row.passRate }}%</span>
          </template>
        </el-table-column>
        <el-table-column prop="defectType" label="主要缺陷" />
        <el-table-column prop="inspector" label="检验员" />
        <el-table-column prop="remark" label="备注" show-overflow-tooltip />
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="pagination.currentPage"
          :page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts" name="qualityReport">
import { ref, reactive, onMounted, nextTick } from "vue";
import type { FormInstance } from "element-plus";
import { ElMessage } from "element-plus";
import { Download } from "@element-plus/icons-vue";
import * as echarts from "echarts";

const loading = ref(false);
const tableData = ref([]);
const searchFormRef = ref<FormInstance>();

// 图表引用
const qualityTrendChart = ref();
const defectReasonChart = ref();
const productQualityChart = ref();
const inspectionTypeChart = ref();

// 查询表单
const searchForm = reactive({
  dimension: "DAY",
  dateRange: [],
  productCategory: "",
  inspectionType: ""
});

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 统计数据
const statsData = reactive({
  totalInspections: 1256,
  overallPassRate: 96.8,
  defectRate: 3.2,
  reworkRate: 2.1
});

// 获取检验类型标签
const getInspectionTypeTag = (type: string) => {
  const typeMap: Record<string, string> = {
    FIRST_PIECE: "primary",
    PROCESS: "info",
    FINAL: "success"
  };
  return typeMap[type] || "info";
};

// 获取检验类型文本
const getInspectionTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    FIRST_PIECE: "首件检验",
    PROCESS: "过程检验",
    FINAL: "最终检验"
  };
  return typeMap[type] || type;
};

// 获取合格率样式
const getPassRateClass = (rate: number) => {
  if (rate >= 98) return "rate-excellent";
  if (rate >= 95) return "rate-good";
  if (rate >= 90) return "rate-normal";
  return "rate-poor";
};

// 初始化图表
const initCharts = () => {
  nextTick(() => {
    // 质量趋势图
    if (qualityTrendChart.value) {
      const trendChart = echarts.init(qualityTrendChart.value);
      const trendOption = {
        tooltip: { trigger: 'axis' },
        legend: { data: ['合格率', '不良率', '返工率'] },
        xAxis: {
          type: 'category',
          data: ['1月', '2月', '3月', '4月', '5月', '6月']
        },
        yAxis: { type: 'value', max: 100 },
        series: [
          {
            name: '合格率',
            type: 'line',
            data: [95.2, 96.1, 94.8, 96.5, 97.2, 96.8]
          },
          {
            name: '不良率',
            type: 'line',
            data: [3.8, 3.2, 4.1, 2.8, 2.1, 2.5]
          },
          {
            name: '返工率',
            type: 'line',
            data: [2.1, 1.8, 2.3, 1.5, 1.2, 1.7]
          }
        ]
      };
      trendChart.setOption(trendOption);
    }

    // 不合格原因分析图
    if (defectReasonChart.value) {
      const reasonChart = echarts.init(defectReasonChart.value);
      const reasonOption = {
        tooltip: { trigger: 'item' },
        legend: { orient: 'vertical', left: 'left' },
        series: [
          {
            name: '不合格原因',
            type: 'pie',
            radius: '50%',
            data: [
              { value: 35, name: '尺寸超差' },
              { value: 28, name: '外观缺陷' },
              { value: 20, name: '功能异常' },
              { value: 12, name: '材料问题' },
              { value: 5, name: '其他' }
            ]
          }
        ]
      };
      reasonChart.setOption(reasonOption);
    }

    // 产品质量对比图
    if (productQualityChart.value) {
      const productChart = echarts.init(productQualityChart.value);
      const productOption = {
        tooltip: { trigger: 'axis' },
        legend: { data: ['智能手机', '工业机器人', '精密仪器'] },
        xAxis: {
          type: 'category',
          data: ['1月', '2月', '3月', '4月', '5月', '6月']
        },
        yAxis: { type: 'value', max: 100 },
        series: [
          {
            name: '智能手机',
            type: 'bar',
            data: [98.2, 97.8, 98.5, 98.1, 98.7, 98.3]
          },
          {
            name: '工业机器人',
            type: 'bar',
            data: [94.5, 95.2, 93.8, 95.8, 96.1, 95.5]
          },
          {
            name: '精密仪器',
            type: 'bar',
            data: [96.8, 97.1, 96.2, 97.5, 97.8, 97.2]
          }
        ]
      };
      productChart.setOption(productOption);
    }

    // 检验类型分布图
    if (inspectionTypeChart.value) {
      const typeChart = echarts.init(inspectionTypeChart.value);
      const typeOption = {
        tooltip: { trigger: 'axis' },
        legend: { data: ['首件检验', '过程检验', '最终检验'] },
        xAxis: {
          type: 'category',
          data: ['周一', '周二', '周三', '周四', '周五', '周六']
        },
        yAxis: { type: 'value' },
        series: [
          {
            name: '首件检验',
            type: 'bar',
            stack: '总量',
            data: [15, 18, 12, 20, 16, 8]
          },
          {
            name: '过程检验',
            type: 'bar',
            stack: '总量',
            data: [45, 52, 38, 58, 48, 25]
          },
          {
            name: '最终检验',
            type: 'bar',
            stack: '总量',
            data: [25, 28, 22, 32, 26, 15]
          }
        ]
      };
      typeChart.setOption(typeOption);
    }
  });
};

// 获取表格数据
const getTableData = async () => {
  loading.value = true;
  try {
    // 模拟数据
    const mockData = [
      {
        date: "2024-01-15",
        productName: "智能手机X1",
        inspectionType: "FINAL",
        inspectionQuantity: 100,
        passQuantity: 98,
        failQuantity: 2,
        passRate: 98.0,
        defectType: "外观划痕",
        inspector: "张三",
        remark: "轻微划痕，已返工处理"
      },
      {
        date: "2024-01-15",
        productName: "工业机器人A1",
        inspectionType: "PROCESS",
        inspectionQuantity: 10,
        passQuantity: 9,
        failQuantity: 1,
        passRate: 90.0,
        defectType: "精度超差",
        inspector: "李四",
        remark: "重新校准后合格"
      },
      {
        date: "2024-01-15",
        productName: "精密仪器C1",
        inspectionType: "FIRST_PIECE",
        inspectionQuantity: 5,
        passQuantity: 5,
        failQuantity: 0,
        passRate: 100.0,
        defectType: "-",
        inspector: "王五",
        remark: "首件检验合格"
      }
    ];
    
    tableData.value = mockData;
    pagination.total = mockData.length;
  } catch (error) {
    console.error("获取质量报表数据失败:", error);
    ElMessage.error("获取质量报表数据失败");
  } finally {
    loading.value = false;
  }
};

// 查询
const handleSearch = () => {
  pagination.currentPage = 1;
  getTableData();
  initCharts();
};

// 重置
const handleReset = () => {
  if (!searchFormRef.value) return;
  searchFormRef.value.resetFields();
  pagination.currentPage = 1;
  getTableData();
  initCharts();
};

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  getTableData();
};

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  getTableData();
};

// 导出报表
const handleExport = () => {
  ElMessage.info("导出质量报表功能开发中");
};

// 页面加载时获取数据
onMounted(() => {
  getTableData();
  initCharts();
});
</script>

<style scoped>
.report-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
}

.stat-item {
  padding: 20px;
}

.stat-value {
  font-size: 32px;
  font-weight: bold;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.inspection-count {
  color: #409eff;
}

.pass-rate {
  color: #67c23a;
}

.defect-rate {
  color: #f56c6c;
}

.rework-rate {
  color: #e6a23c;
}

.charts-container {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.pass-quantity {
  color: #67c23a;
  font-weight: bold;
}

.fail-quantity {
  color: #f56c6c;
  font-weight: bold;
}

.rate-excellent {
  color: #67c23a;
  font-weight: bold;
}

.rate-good {
  color: #409eff;
  font-weight: bold;
}

.rate-normal {
  color: #e6a23c;
  font-weight: bold;
}

.rate-poor {
  color: #f56c6c;
  font-weight: bold;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>